package com.opennews.openplatform.familyexpenseapi.jooq

import org.jooq.Condition
import org.jooq.DSLContext
import org.jooq.TableLike
import org.jooq.impl.DSL
import org.springframework.stereotype.Component

@Component
class DSLContextWrapper(private val dslContext: DSLContext) {
    fun count(table: TableLike<*>, condition: Condition? = null): Int {
        val query = dslContext.selectCount().from(table)

        condition?.let {
            query.where(it)
        }

        return query.fetchOneInto(Int::class.java) ?: 0
    }

    fun count(table: TableLike<*>): Int = count(table, null)

    fun exists(table: TableLike<*>, condition: Condition? = null): Boolean {
        val subquery = dslContext.selectOne().from(table)

        condition?.let {
            subquery.where(it)
        }

        return dslContext
            .select(DSL.exists(subquery))
            .fetchOneInto(Boolean::class.java) ?: false
    }

    fun exists(table: TableLike<*>): Boolean = exists(table, null)
}